package com.tt.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tt.reggie.common.R;
import com.tt.reggie.entity.User;
import com.tt.reggie.service.UserService;
import com.tt.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user,HttpSession request){
        String phone = user.getPhone();

        String subject = "瑞吉餐购登录验证码";
        if(StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            String context = "欢迎使用瑞吉餐购，登录验证码为:"+code+",五分钟有效，请妥善保管！";
            userService.sendMsg(phone,subject,context);
            //将验证码加入redis中
            stringRedisTemplate.opsForValue().set(phone,code,1, TimeUnit.MINUTES);
//            request.setAttribute(phone,code);
            return R.success("验证码发送成功！");
        }
        return R.error("验证码发生失败！");
    }


    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession request){
        log.info(map.toString());
        //获取前端输入的邮箱
        String emile = map.get("phone").toString();

        //获取前端输入的验证码
        String code = map.get("code").toString();

        //session中保存的code
//        Object codeInSession = request.getAttribute(emile);
        String codeInRedis = stringRedisTemplate.opsForValue().get(emile);
        if(codeInRedis!=null && codeInRedis.equals(code)){
            //登录成功，判断是否为第一次登录
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,emile);
            User one = userService.getOne(userLambdaQueryWrapper);
            if(one==null){
               User user = new User();
               user.setPhone(emile);
               user.setStatus(1);
               request.setAttribute("user",user.getId());
               userService.save(user);
               return R.success(user);
            }
            request.setAttribute("user",one.getId());
            //若登录成功，则删除redis中保存的验证码
            stringRedisTemplate.delete(emile);
            return R.success(one);
        }

        return R.error("登录失败！");
    }

}
